﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;

namespace CommonHelper
{
    public class FileHelper
    {
        private static string _Path = Assembly.GetExecutingAssembly().Location;
        private static string _SqlPath = _Path.Substring(0, _Path.IndexOf("bin")) + "Sql";

        /// <summary>
        /// 获取目录下的所有Sql文件
        /// </summary>
        /// <returns></returns>
        public static IList<StringBuilder> GetAllSql()
        {
            List<string> sqlFileList = new List<string>();
            var sbList = new List<StringBuilder>();
            List<string> AllFileList = Directory.GetFiles(_SqlPath).ToList();
            foreach (var file in AllFileList)
            {
                if (file.IndexOf(".sql") != -1)
                {
                    sqlFileList.Add(file);
                }
            }

            sqlFileList.Sort();

            foreach (var sqlFile in sqlFileList)
            {
                GetSql(sqlFile, sbList);
            }

            return sbList;
        }

        /// <summary>
        /// 获取每个具体目录下的Sql
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="sbList"></param>
        private static void GetSql(string filePath, List<StringBuilder> sbList)
        {
            if (File.Exists(filePath))
            {
                using (StreamReader sr = new StreamReader(filePath, Encoding.GetEncoding("GBK")))
                {
                    var sbStr = new StringBuilder();
                    while(!sr.EndOfStream)
                    {
                        sbStr.Append(sr.ReadLine());
                    }

                    sbList.Add(sbStr);
                }
            }
        }
    }
}
